#!/bin/sh
#
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Set activate date in VPD. This script should be called during OOBE to write
# down the activate date.
#
# Since OOBE can be invoked multiple times, this script should check if the
# activate date has been written. If yes, do nothing.
#
# Example:
#   activate_date.sh          set the activate date to now if not set yet
#   activate_date.sh --clean  reset the activate date to an empty string.
#

# VPD program location
VPD="/usr/sbin/vpd"

# The field name of activate date in VPD
FIELD_NAME="ActivateDate"

# Partition to store activate date
PARTITION="RW_VPD"


die() {
  echo "$*" >&2
  exit 1
}


write_activate_date() {
  $VPD -i "$PARTITION" -s "$FIELD_NAME=$1" || die "vpd returns ERROR."
}

clean_activate_date() {
  echo "Clean Activate Date."
  write_activate_date ""
}

#
# main()
#

if [ "$1" = "--clean" ]; then
  CLEAN=1
else
  CLEAN=0
fi

# Get the current value in VPD. The output format is followed:
#
#   "ActivateDate"="2011-02-14 09:23:56"
#
# Remove those double-quotes and equal mark.
output=$("$VPD" -i "$PARTITION" -l) || die "vpd read error."
activateDate=$(echo $output | grep $FIELD_NAME |
               awk -F= '{print $2}' | tr -d '"')

# If 1. no VPD entry is set, or
#    2. ActivateDate is empty string,
#   Then, write down current time into VPD.
if [ -z "$activateDate" ]; then
  if [ $CLEAN -eq 1 ]; then
    echo "Activate Date is not set yet. --clean is ignored."
  else
    # No activate date is set. Use current UTC time.
    nowDate=$(date --utc "+%Y-%m-%d %H:%M:%S")
    echo "Setting Activate Date to $nowDate."
    write_activate_date "$nowDate"
  fi
  echo "Done."
else
  if [ $CLEAN -eq 1 ]; then
    clean_activate_date
    echo "Done."
  else
    # An activate date is set. Do nothing.
    echo "Activate Date has been set to $activateDate."
  fi
fi
